#include "animSprite.h"
#include <iostream>
#include <assert.h>
#include <string>

namespace game
{

sf::Vector2u get2dFrom1d(unsigned int pI, unsigned int pWidth)
{
	sf::Vector2u lP;//int lX,lY;
	lP.x = pI % pWidth;
	lP.y = pI - lP.x;
	lP.y = lP.y/pWidth;
	return lP;
}

game::SpriteSheetManager * animSprite::getManager()
{
	return _manager;
}

animSprite::animSprite(animSpriteData data, SpriteSheetManager * manager)
{
	_manager = manager;
	_frameId = 0;
	_frameCount = 0;
	_spriteSheetId = data._sprite_sheet_id;
	if (data._anim_count > 0)
	for (int i = 0; i < data._anim_count; i++)
	{
		if (data._anim_ids[i] > 1000){std::cout << "anim id error " <<std::endl;}
		addFrame(data._anim_ids[i]);
	}
}

animSprite::~animSprite(void)
{
}


void animSprite::addFrame(int pSpriteId)
{
	_spriteId[_frameCount] = pSpriteId;
	_frameCount++;
}

void animSprite::draw(sf::RenderWindow &pWindow)
{
	int lWidth =  getManager()->getSheetIndexWidth(_spriteSheetId);
	int lSpacing = getManager()->getSheetSpacing(_spriteSheetId);
	sf::Vector2u lPos;	
	lPos =get2dFrom1d(_spriteId[_frameId],lWidth);// sf::Vector2u(0,0);//
	sf::IntRect lRect(lPos.x*lSpacing,lPos.y*lSpacing,lSpacing,lSpacing);
	getManager()->getSprite(_spriteSheetId)->setTextureRect(lRect);
	pWindow.draw(*getManager()->getSprite(_spriteSheetId));
	_frameId++;
	if (_frameId == _frameCount){_frameId= 0;}
}

void animSprite::updatePosition(sf::Vector2u pPos)
{
	getManager()->getSprite(_spriteSheetId)->setPosition(pPos.x,pPos.y);//optimize / Where does the position update go?
}

void animSprite::updatePositionAndDraw(sf::RenderWindow &pWindow, sf::Vector2u pPos)
{
	draw(pWindow);
	updatePosition(pPos);
}

sf::Color animSprite::getColorAtPoint(sf::Vector2i p)
{
	return getManager()->getTexture(_frameId)->copyToImage().getPixel(p.x,p.y);
}
sf::Image animSprite::getImage(int frame)
{
	return getManager()->getTexture(frame)->copyToImage();
}

}